import * as vscode from 'vscode'
import { NAME } from '../config'

const DOUBLE_QUOTE_REGEXP = /"/g

export class Logger implements vscode.Disposable {
  private readonly channel: vscode.OutputChannel

  constructor() {
    this.channel = vscode.window.createOutputChannel(NAME)
  }

  public dispose() {
    this.channel.dispose()
  }

  public log(message: string) {
    const date = new Date()
    const timestamp =
      date.getFullYear() +
      '-' +
      pad2(date.getMonth() + 1) +
      '-' +
      pad2(date.getDate()) +
      ' ' +
      pad2(date.getHours()) +
      ':' +
      pad2(date.getMinutes()) +
      ':' +
      pad2(date.getSeconds()) +
      '.' +
      pad3(date.getMilliseconds())
    this.channel.appendLine('[' + timestamp + '] ' + message)
  }

  public cmd(cmd: string, args: string[]) {
    this.log(
      '> ' +
        cmd +
        ' ' +
        args
          .map((arg) =>
            arg === ''
              ? '""'
              : arg.startsWith('--format=')
              ? '--format=...'
              : arg.includes(' ')
              ? '"' + arg.replace(DOUBLE_QUOTE_REGEXP, '\\"') + '"'
              : arg
          )
          .join(' ')
    )
  }

  public error(message: string) {
    this.log('ERROR: ' + message)
  }

  public warn(message: string) {
    this.log('WARN: ' + message)
  }
}

function pad2(n: number) {
  return (n > 9 ? '' : '0') + n
}

function pad3(n: number) {
  return (n > 99 ? '' : n > 9 ? '0' : '00') + n
}
